<script setup>
import { onMounted, ref } from 'vue'
import { sendData } from "@/api/index"
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useWxdataStore } from '@/stores/wxdata';
import { UseDataStore } from '@/stores/basicData';
//调用实例
const route = useRoute()
const router = useRouter()
const UserStore = useUserStore()
const wxdataStore = useWxdataStore()
const DataStore = UseDataStore()
//标签栏
const active = ref('index')
//展示次数面板
//Array.from方法：{ length: 10 }表示创建了一个长度为10的数组
//(_, index)它接收两个参数，第一个参数（当前元素的值）在这里没有被使用（用 _ 表示），只使用了第二个参数（当前元素的索引）
const actions = Array.from({ length: 7 }, (_, index) => ({
    name: `${index + 1}`
}))
//表单校验规则
const rules = {
    userId: [
        { required: true, message: "请填写乐跑id" },
        { validator: (val) => /^\d{8}$/.test(val), message: "乐跑id必须是的八位数字" },
    ],
    times: [{ required: true, message: "请选择次数" }],
    startDate: [{ required: true, message: "请选择日期" }],
}
//数据
const data = ref({
    userId: "",
    times: "",
    km: "1",
    startDate: "",
    amount: ""
})
//次数面板
const showTimes = ref(false)

//日历面板
const showCalendar = ref(false)
//获取日期
const formatDate = (startDate) => {
    return startDate.getFullYear() + "-" + (startDate.getMonth() + 1) + "-" + startDate.getDate();
}
//日历确认按钮
const confirmDate = (startDate) => {
    data.value.startDate = formatDate(startDate)
    showCalendar.value = false
}
//计算总额
const totalAmount = () => {
    data.value.amount = ((data.value.km === '1' ? 1.5 : 2.5) * data.value.times) * 100
}
//表单实例
const formRef = ref(null)
//提交按钮
const submit = async () => {
    totalAmount()
    //保证全部表单相校验通过再发请求
    await formRef.value?.validate() // 可选链，防止提交时无formRef
    //发请求
    let result = await sendData(data.value)
    if (result.code === 1) {
        localStorage.setItem('id', data.value.userId)
        wxdataStore.updateWxdata(result.data)
        DataStore.upData(data.value)
        router.push({
            path: '/pay'
        })
    }
}
//标签页切换
const onChange = () => {
    router.push({
        path: '/show'
    })
}
onMounted(() => {
    //将路由携带的token传到仓库
    UserStore.updateToken(route.query.token)
})
</script>

<template>
    <div class="top">授权网站:https://www.yjercf.buzz/zhiyinsq/#/bdlp</div>
    <div class="top container" style="color: red;">每次使用必须授权，这个网站必须用浏览器打开！！！(最好用电脑)</div>
    <div class="mt15">
        <van-form ref="formRef">
            <van-cell-group inset>
                <!-- id -->
                <van-field v-model="data.userId" name="乐跑id" label="乐跑id" placeholder="请输入您的乐跑id"
                    :rules="rules.userId"></van-field>
                <!-- timer -->
                <van-field v-model="data.times" is-link readonly label="乐跑次数" placeholder="点击选择次数"
                    @click="showTimes = true" :rules="rules.times"></van-field>
                <van-action-sheet v-model:show="showTimes" :actions="actions" close-on-click-action
                    @select="(item) => (data.times = item.name)"></van-action-sheet>
                <!-- km -->
                <van-field name="radio" label="乐跑公里数">
                    <template #input>
                        <van-radio-group v-model="data.km" direction="horizontal">
                            <van-radio name="1">1公里</van-radio>
                            <van-radio name="3">3公里</van-radio>
                        </van-radio-group>
                    </template>
                </van-field>
                <!-- time -->
                <van-field v-model="data.startDate" is-link readonly name="calendar" label="开始时间" placeholder="点击选择日期"
                    @click="showCalendar = true" :rules="rules.startDate"></van-field>
                <van-calendar v-model:show="showCalendar" @confirm="confirmDate"></van-calendar>
            </van-cell-group>
            <div class="m16">
                <van-button round block type="primary" native-type="submit" @click="submit">
                    下单
                </van-button>
            </div>

        </van-form>
    </div>
    <!-- 底层标签页 -->
    <van-tabbar class="tabbar" v-model="active" @change="onChange">
        <van-tabbar-item icon="wap-home" name="index">主页</van-tabbar-item>
        <van-tabbar-item icon="bars" name="order">订单</van-tabbar-item>
    </van-tabbar>
</template>

<style scoped>
body {
    background-color: #f7f7f7;
}

.top {
    width: 100%;
    height: 32px;
    text-align: center;
    line-height: 32px;
}

.mt15 {
    margin-top: 30px;
}

.m16 {
    margin: 16px;
}

.tips {
    margin-top: 30px;
}
</style>
